package com.project.config;

import com.project.bean.PowerBean;
import com.project.bean.UserBean;
import com.project.dao.IPowerDao;
import com.project.dao.IUserDao;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author RJ
 * @date 2022/10/13 16:26
 */
@Component
public class MyRealm extends AuthorizingRealm {
    @Resource
    IUserDao userDao;

    @Resource
    IPowerDao powerDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        UserBean userBean = (UserBean) principalCollection.getPrimaryPrincipal();
        //用户查询权限
        List<PowerBean> list = powerDao.powerListByUserName(userBean.getUserName());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        list.stream().filter(power -> power != null && !power.getPowerURI().equals(""))
                .forEach(powerEntity -> info.addStringPermission(powerEntity.getPowerURI()));
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        char[] passArray = token.getPassword();
        String userName = token.getUsername();
        String userPwd = String.valueOf(passArray);
        System.out.println(userPwd);
        //从数据库查询用户是否存在
        UserBean userBean = userDao.findUserByPwd(userName, userPwd);
        if (userBean != null) {
            return new SimpleAuthenticationInfo(userBean, userPwd, userName);
        }

        return null;
    }
}
